//
//  UIView+TipView.m
//  JQKit
//
//  Created by JQZ on 2017/11/24.
//  Copyright © 2017年 JQZ. All rights reserved.
//

#import "UIView+TipView.h"
#import "NSObject+Association.h"

@interface UIView (TipViewPrivate)

@property (nonatomic, strong) id __tipview_userData;

@property (nonatomic, copy) void (^__tipview_retryAction)(id userData);

@end

@implementation UIView (TipViewPrivate)

- (void)set__tipview_userData:(id)__tipview_userData
{
    [self setAssociatedObject:__tipview_userData forKey:@"__tipview_userData" association:AssociationStrong isAtomic:NO];
}
- (id)__tipview_userData
{
    return [self associatedObjectForKey:@"__tipview_userData"];
}

- (void)set__tipview_retryAction:(void (^)(id))__tipview_retryAction
{
    [self setAssociatedObject:__tipview_retryAction forKey:@"__tipview_retryAction" association:AssociationStrong isAtomic:NO];
}
- (void (^)(id))__tipview_retryAction
{
    return [self associatedObjectForKey:@"__tipview_retryAction"];
}

@end



#pragma mark - ## UIView (TipView)
@implementation UIView (TipView)

- (void)showTipView:(UIView *)tipView retryAction:(void (^)(id userData))retryAction
{
    [self showTipView:tipView userData:nil retryAction:retryAction];
}

- (void)showTipView:(UIView *)tipView userData:(id)userData retryAction:(void (^)(id userData))retryAction
{
    if (!tipView) {
        return;
    }
    if (tipView.superview) {
        [tipView removeFromSuperview];
    }
    
    [self setTipView:tipView];
    [self set__tipview_userData:userData];
    [self set__tipview_retryAction:retryAction];
    [tipView setFrame:self.bounds];
    [self addSubview:tipView];
    
    if (retryAction) {
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(__didClickTipView)];
        [tipView addGestureRecognizer:tapGR];
    }
}

- (void)removeTipView
{
    if (self.tipView) {
        [self.tipView removeFromSuperview];
    }
}

- (void)setTipView:(UIView *)tipView
{
    [self setAssociatedObject:tipView forKey:@"__tipView" association:AssociationStrong isAtomic:NO];
}
- (UIView *)tipView
{
    return [self associatedObjectForKey:@"__tipView"];
}

#pragma mark - # Event Response
- (void)__didClickTipView
{
    [self removeTipView];
    if (self.__tipview_retryAction) {
        self.__tipview_retryAction(self.__tipview_retryAction);
    }
}


@end
